﻿//     Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Linq;
using System.Web;

namespace Microsoft.Gateway.Tracing
{
    public class AuthHook : IGatewayModuleInit
    {
        private const string GatewayRemoteUser = "GW-REMOTE-USER";

        public void Init(System.Web.HttpApplication context)
        {
            context.AuthenticateRequest += OnAuthenticateRequest;
            context.PreSendRequestHeaders += OnPreSendRequestHeaders;
        }

        void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            var app = sender as HttpApplication;
            if (app != null && app.User != null)
            {
                app.Response.AppendCookie(new HttpCookie("UPN", app.User.Identity.Name));
            }
        }

        void OnAuthenticateRequest(object sender, EventArgs e)
        {
             var context = ((HttpApplication)sender).Context;
            var value = context.Request.ServerVariables["REMOTE_USER"];
            context.Response.Headers.Set(GatewayRemoteUser, string.IsNullOrEmpty(value) ? "" : value);
        }
    }
}
